{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "C:\\ProgramData\\Anaconda3\\lib\\site-packages\\h5py\\__init__.py:34: FutureWarning: Conversion of the second argument of issubdtype from `float` to `np.floating` is deprecated. In future, it will be treated as `np.float64 == np.dtype(float).type`.\n",
      "  from ._conv import register_converters as _register_converters\n"
     ]
    }
   ],
   "source": [
    "import tensorflow as tf\n",
    "import numpy as np"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "# 使用nunpy来生成100个随机点（样本）\n",
    "x_data = np.random.rand(100)\n",
    "y_data = x_data * 0.1 + 0.2\n",
    "\n",
    "# 构造一个线性模型\n",
    "b = tf.Variable(0.)\n",
    "k = tf.Variable(0.)\n",
    "y = k * x_data + b"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "# 定义一个二次代价函数\n",
    "loss = tf.reduce_mean(tf.square(y_data - y))\n",
    "\n",
    "# 定义一个梯度下降法来进行训练的优化器\n",
    "optimizer = tf.train.GradientDescentOptimizer(0.2)\n",
    "\n",
    "# 最小化代价函数\n",
    "train = optimizer.minimize(loss)\n",
    "\n",
    "# 初始化变量\n",
    "init = tf.global_variables_initializer()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "0 [0.05681972, 0.1012128]\n",
      "20 [0.10584582, 0.19670016]\n",
      "40 [0.10358142, 0.19797839]\n",
      "60 [0.10219413, 0.19876146]\n",
      "80 [0.10134423, 0.19924122]\n",
      "100 [0.10082354, 0.19953513]\n",
      "120 [0.10050453, 0.19971521]\n",
      "140 [0.1003091, 0.19982553]\n",
      "160 [0.10018938, 0.1998931]\n",
      "180 [0.10011602, 0.19993451]\n"
     ]
    }
   ],
   "source": [
    "with tf.Session() as sess:\n",
    "    \n",
    "    # 初始化变量\n",
    "    sess.run(init)\n",
    "    \n",
    "    # 迭代\n",
    "    for _ in range(200):\n",
    "        \n",
    "        sess.run(train)\n",
    "        \n",
    "        if _ % 20 == 0:\n",
    "            \n",
    "            print(_, sess.run([k, b]))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.6.2"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
